/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.tags;

import com.apache.client.InfoReleaseCoreCleint;
import com.apache.database.model.Page;
import com.apache.portal.common.enums.InfoMethodEnum;
import com.apache.tools.ConfigUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.*;

/**
 * description:  消息通知标签
 *
 * @author Hou Dayu 创建时间：2016-8-29
 */
@SuppressWarnings("serial")
public class DynamicInfoTag extends TagSupport {

    private String doCode;//枚举代码

    private String pageSize;//记录数

    private String sortCode;//动态表代码

    private String tabName;//主子表代码

    private String sqlQuery;//查询条件

    private String attrName;//属性名

    public int doStartTag() throws JspException {
        try {
            HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
            Map<String, Object> params = getMethodParams(request);
            if (StrUtil.isNotNull(sortCode)) {
                params.put("sortCode", sortCode);
            }
            if (StrUtil.isNotNull(tabName)) {
                params.put("tabName", tabName);
            }
            json2map1(params, request);
            switch (InfoMethodEnum.getName(doCode)) {
            case List:
                params.put("orderby", "create_time desc");
                Object objs = InfoReleaseCoreCleint.getInstance().selectInfo(params);
                request.setAttribute(attrName, objs);
                break;
            case Pages:
                if (StrUtil.isNotNull(String.valueOf(params.get("infoTitle")))) {
                    params.put("infoTitle",
                            "like '%" + String.valueOf(params.get("infoTitle")) + "%'");
                }
                if (StrUtil.isNotNull(String.valueOf(params.get("isTop")))) {
                    params.put("orderby", "is_top_time desc");//按照推荐查询，就以推荐时间倒序
                } else {
                    params.put("orderby", "create_time desc");
                }
                params.put("pageSize", StrUtil.doNull(pageSize, "10"));
                params.put("pageIndex",
                        StrUtil.doNull(String.valueOf(params.get("pageIndex")), "1"));
                System.out.println(params);
                Object page = InfoReleaseCoreCleint.getInstance().selectInfo(params);
                gotoPageInfo(page, request);
                break;
            case View:
                Object obj = InfoReleaseCoreCleint.getInstance().selectSingle(params);
                if (null != obj) {
                    request.setAttribute(attrName, obj);
                }
                break;
            case Sublist:
                subTables(params);
                Object subObjs = InfoReleaseCoreCleint.getInstance().selectMasterSlaveInfo(params);
                request.setAttribute(attrName, subObjs);
                break;
            case Subpages:
                subTables(params);
                params.put("pageSize", StrUtil.doNull(pageSize, "10"));
                params.put("pageIndex",
                        StrUtil.doNull(String.valueOf(params.get("pageIndex")), "1"));
                Object subPage = InfoReleaseCoreCleint.getInstance().selectMasterSlaveInfo(params);
                gotoPageInfo(subPage, request);
                break;
            case Subview:
                subTables(params);
                Object subobj = InfoReleaseCoreCleint.getInstance().selectMasterSlaveSingle(params);
                if (null != subobj) {
                    request.setAttribute(attrName, subobj);
                }
                break;
            case ufsql://根据sql综合查询
                selectUnionFormDataBySql(request, params);
                break;
            case Default:
                break;
            }
        } catch (Exception e) {
            return super.SKIP_BODY;
        }
        return super.EVAL_BODY_INCLUDE;
    }

    private void subTables(Map<String, Object> params) {
        String sortCodes[] = tabName.split(",");
        params.put("mainSortCode", sortCodes[0]);
        params.put("subSortCode", sortCodes[1]);
        params.remove("tableName");
    }

    private void selectUnionFormDataBySql(HttpServletRequest request, Map<String, Object> params) {
        String[] scs = new String[] {};
        String sortCodeSingle = String.valueOf(params.get("sortCodeSingle"));
        if (StrUtil.isNotNull(sortCodeSingle)) {
            scs = new String[] { sortCodeSingle };
        } else {
            String sortCodeStr = String.valueOf(params.get("sortCodeStr"));
            scs = sortCodeStr.split(",");
        }
        StringBuffer sqlStr = new StringBuffer("select * from ( ");
        for (int i = 0; i < scs.length; i++) {
            String str = scs[i];
            sqlStr.append("select  '" + str
                    + "' as sort_code,info_id,info_title,info_type,is_top,is_top_time,pic_url, status,create_time,create_user,industry,info_price from pub_"
                    + str);
            if (i < scs.length - 1) {
                sqlStr.append(" union ");
            }
        }
        sqlStr.append(" ) t");
        sqlStr.append(" where 1=1 ");
        if (StrUtil.isNotNull(String.valueOf(params.get("createUser")))) {
            sqlStr.append(" and t.create_user='" + String.valueOf(params.get("createUser")) + "' ");
        }
        if (StrUtil.isNotNull(String.valueOf(params.get("infoTitle")))) {
            sqlStr.append(
                    " and t.info_title like '%" + String.valueOf(params.get("infoTitle")).trim()
                            + "%' ");
        }
        if (StrUtil.isNotNull(String.valueOf(params.get("status")))) {
            sqlStr.append(" and t.status = '" + String.valueOf(params.get("status")) + "' ");
        }
        if (StrUtil.isNotNull(String.valueOf(params.get("isTop")))) {
            sqlStr.append(" and t.is_top = '" + String.valueOf(params.get("isTop")) + "' ");
            sqlStr.append(" order by t.is_top_time desc");//按照推荐查询，就以推荐时间倒序
        } else {
            sqlStr.append(" order by t.create_time desc");
        }
        params.put("dynamicSql", sqlStr.toString());
        System.out.println(params.get("dynamicSql"));
        params.put("pageSize", StrUtil.doNull(pageSize, "10"));
        params.put("pageIndex", StrUtil.doNull(String.valueOf(params.get("pageIndex")), "1"));
        Object pageList = InfoReleaseCoreCleint.getInstance().selectInfo(params);
        gotoPageInfo(pageList, request);
    }

    private void gotoPageInfo(Object obj, HttpServletRequest request) {
        if (null != obj) {
            Page page = (Page) obj;
            request.setAttribute(attrName, page.getPageObjects());
            request.setAttribute("pageSize", page.getPageSize());
            request.setAttribute("pageIndex", page.getPageNeeded());
            request.setAttribute("total", page.getCount());
        }
    }

    /**
     * json转map
     */
    private void json2map1(Map<String, Object> params, HttpServletRequest request) {
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        if (StrUtil.isNotNull(sqlQuery)) {
            JSONObject jsonObject = JSONObject.fromObject(sqlQuery);
            Map<String, Object> map1 = JSONObject.fromObject(jsonObject);
            String selectUser = String.valueOf(map1.get("selectUser"));
            if ("true".equals(selectUser)) {
                params.put("createUser", loginUser.getUserEname());
            }
            if (map1.containsKey("nowtimeafter")) {
                map1.put(String.valueOf(map1.get("nowtimeafter")),
                        "between " + (System.currentTimeMillis()) + " and " + DateUtils
                                .after(new Date(), 30).getTime());
            }
            //			System.out.println(map1.get("pubEndTime"));
            map1.remove("selectUser");
            params.putAll(map1);
        } else {
            //前台登录用户就查不出所有的信息了
            //			if (null != loginUser) {
            //				params.put("createUser", loginUser.getUserEname());
            //			}
        }
    }

    @SuppressWarnings("rawtypes")
    private Map<String, Object> getMethodParams(HttpServletRequest request) {
        Map<String, Object> bodyMap = new HashMap<String, Object>();
        bodyMap.put("Client-IP", RequestTools.getIp(request));
        Set keSet = request.getParameterMap().entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey();
            Object ov = me.getValue();
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
            } else {
                value[0] = ov.toString();
            }
            if (value.length > 0) {
                if (String.valueOf(ok).startsWith("like_") && StrUtil.isNotNull(value[0])) {
                    bodyMap.put(String.valueOf(ok).replaceAll("like_", ""),
                            "like '%" + value[0] + "%'");
                } else if (String.valueOf(ok).startsWith("between_") && StrUtil
                        .isNotNull(value[0])) {
                    String[] str = value[0].split(":");
                    bodyMap.put(String.valueOf(ok).replaceAll("between_", ""),
                            "between " + str[0] + " and " + str[1]);
                } else {
                    bodyMap.put(ok.toString(), value[0]);
                    request.setAttribute(ok.toString(), value[0]);
                }
            }
        }
        String sysPass = ConfigUtil.getInstance().interfacePass();
        bodyMap.put("sysPass", sysPass);
        return bodyMap;
    }

    public String getDoCode() {
        return doCode;
    }

    public void setDoCode(String doCode) {
        this.doCode = doCode;
    }

    public String getPageSize() {
        return pageSize;
    }

    public void setPageSize(String pageSize) {
        this.pageSize = pageSize;
    }

    public String getSortCode() {
        return sortCode;
    }

    public void setSortCode(String sortCode) {
        this.sortCode = sortCode;
    }

    public String getTabName() {
        return tabName;
    }

    public void setTabName(String tabName) {
        this.tabName = tabName;
    }

    public String getSqlQuery() {
        return sqlQuery;
    }

    public void setSqlQuery(String sqlQuery) {
        this.sqlQuery = sqlQuery;
    }

    /**
     * description:  主子表代码(如:主表,子表)
     */
    public String getAttrName() {
        return attrName;
    }

    public void setAttrName(String attrName) {
        this.attrName = attrName;
    }

}
